package com.lzs.chuku.controller;


import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzs.chuku.feign.KucunFeign;
import com.lzs.chuku.feign.SystemFeign;
import com.lzs.chuku.mapper.UserMapper;
import com.lzs.chuku.service.*;
import com.lzs.entity.*;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘中帅
 * @since 2020-11-23
 */
@RestController
@RequestMapping("/chuku/outorder")
public class OutorderController {
    @Autowired
    private KucunFeign kucunFeign;
    @Autowired
    private PickDetailService pickDetailService;
    @Autowired
    private PickService pickService;
    @Autowired
    private PicktaskService picktaskService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OutorderService outorderService;
    @Autowired
    private OutorderDetailService outorderDetailService;
    @PostMapping("saveOrUpdate")
    @ApiOperation("新增出库订单")
    public R saveOrUpdate(@RequestBody Outorder outorder, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId= JwtUtils.getMemberIdByJwtToken(token);
        User user = userMapper.findUserbyId(userId);
        if (outorder.getId()==null){
            outorder.setState("0");
            outorder.setCreateid(user.getUserId());
            outorder.setCreator(user.getName());
        }
        boolean b = outorderService.saveOrUpdate(outorder);
        if (b){
            return R.ok().message("新增出库成功");
        }
        return R.error().message("新增出库失败");
    }
    @GetMapping("findOutorderById/{id}")
    @ApiOperation("根据id查询出库订单")
    public R findOutorderById(@ApiParam("出库记录id") @PathVariable("id") Long outorderid){
        Outorder outorder = outorderService.getById(outorderid);
        if (outorder!=null){
            return R.ok().message("查询成功").data("outOrder",outorder);
        }
        return R.error().message("查询失败");
    }

    @PostMapping("findOutorderPageBy/{currentPage}/{pageSize}")
    @ApiOperation("条件分页查询")
    public R findOutorderPageBy(@RequestBody Outorder outorder,
                                @PathVariable("currentPage") Integer currentPage,
                                @PathVariable("pageSize") Integer pageSize){
        return outorderService.findOutorderPageBy(outorder,currentPage,pageSize);
    }

    @PostMapping("check")
    @ApiOperation("审核出库单")
    public R check(@RequestBody List<Long>  outorderids,HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId= JwtUtils.getMemberIdByJwtToken(token);
        User user = userMapper.findUserbyId(userId);
        if(outorderids.size()==0)
            return R.error().message("请选择列表中任一订单");
        for (int i = 0; i <outorderids.size() ; i++) {
            Outorder outorder = outorderService.getById(outorderids.get(i));
            if (!outorder.getState().equals("1")){
                return R.error().message("当前状态不符");
            }
        }
        for (int i = 0; i <outorderids.size() ; i++) {
            Outorder outorder = outorderService.getById(outorderids.get(i));
            outorder.setAuditid(userId);
            outorder.setAuditor(user.getName());
            outorder.setAudittime(new Date());
            QueryWrapper<Outorder> wrapper=new QueryWrapper<>();
            wrapper.eq("id",outorderids.get(i));
            outorderService.update(outorder,wrapper);
        }
        return outorderService.changestate(outorderids,"2");
    }

    @PostMapping("rollbackCheck")
    @ApiOperation("撤销审核")
    public R rollbackCheck(@RequestBody List<Long>  outorderids){
        if(outorderids.size()==0)
            return R.error().message("请选择列表中任一订单");
        for (int i = 0; i <outorderids.size() ; i++) {
            Outorder outorder = outorderService.getById(outorderids.get(i));
            if (!outorder.getState().equals("2")){
                return R.error().message("选中状态不符");
            }
        }

        return outorderService.changestate(outorderids,"1");
    }

    @PostMapping("cancelOrder")
    @ApiOperation("取消订单，改变订单状态为9，取消状态")
    public R cancelOrder(@RequestBody List<Long>  outorderids){
        if(outorderids.size()==0)
            return R.error().message("请选择列表中任一订单");
        for (int i = 0; i <outorderids.size() ; i++) {
            Outorder outorder = outorderService.getById(outorderids.get(i));
            if (outorder.getState().equals("6")){
                return R.error().message("选中订单包含已出库的订单，无法取消");
            }else if (outorder.getState().equals("9")){
                return R.error().message("选中订单包含已取消的订单");
            }
        }
        for (int i = 0; i <outorderids.size() ; i++) {
            Outorder outorder = outorderService.getById(outorderids.get(i));
            //已插入明细  把明细删除 状态为未审核 和已审核都是已经插入明细
            if (outorder.getState().equals("2")||outorder.getState().equals("1")){
                QueryWrapper<OutorderDetail> wrapper=new QueryWrapper<>();
                wrapper.eq("pid",outorderids.get(i));
                List<OutorderDetail> list = outorderDetailService.list(wrapper);
                for (int j = 0; j <list.size() ; j++) {
                    OutorderDetail outorderDetail = list.get(i);
                    kucunFeign.updateRealQuantity2(outorderDetail.getLocatorid(),outorderDetail.getCommodityid(),outorderDetail.getWarehouseid(),outorderDetail.getQty());
                }
                outorderDetailService.remove(wrapper);
            }else if (outorder.getState().equals("3")){
                //已生成拣货任务  把生成的拣货任务删除  出库明细删除
                QueryWrapper<OutorderDetail> wrapper=new QueryWrapper<>();
                wrapper.eq("pid",outorderids.get(i));
                List<OutorderDetail> list = outorderDetailService.list(wrapper);
                for (int j = 0; j <list.size() ; j++) {
                    OutorderDetail outorderDetail = list.get(i);
                    kucunFeign.updateRealQuantity2(outorderDetail.getLocatorid(),outorderDetail.getCommodityid(),outorderDetail.getWarehouseid(),outorderDetail.getQty());
                }
                outorderDetailService.remove(wrapper);
                QueryWrapper<Picktask> wrapper1=new QueryWrapper<>();
                wrapper1.eq("outorderid",outorderids.get(i));
                picktaskService.remove(wrapper1);
            }else if (outorder.getState().equals("4")||outorder.getState().equals("5")){
                //拣货中  拣货明细删除  拣货删除 拣货任务删除 出库明细删除
                QueryWrapper<OutorderDetail> wrapper5=new QueryWrapper<>();
                wrapper5.eq("pid",outorderids.get(i));
                List<OutorderDetail> list = outorderDetailService.list(wrapper5);
                for (int j = 0; j <list.size() ; j++) {
                    OutorderDetail outorderDetail = list.get(i);
                    kucunFeign.updateRealQuantity2(outorderDetail.getLocatorid(),outorderDetail.getCommodityid(),outorderDetail.getWarehouseid(),outorderDetail.getQty());
                }
                outorderDetailService.remove(wrapper5);
                //
                QueryWrapper<Picktask> wrapper=new QueryWrapper<>();
                wrapper.eq("outorderid",outorderids.get(i));
                Picktask picktask = picktaskService.getOne(wrapper);
                picktaskService.removeById(picktask.getId());
                QueryWrapper<Pick> wrapper1=new QueryWrapper<>();
                wrapper1.eq("picktaskid",picktask.getId());
                Pick pick = pickService.getOne(wrapper1);
                pickService.remove(wrapper1);
                QueryWrapper<PickDetail> wrapper2=new QueryWrapper<>();
                wrapper2.eq("pid",pick.getId());
                pickDetailService.remove(wrapper2);
            }
        }
        return outorderService.changestate(outorderids,"9");
    }

    @PostMapping("deleteOutorder")
    @ApiOperation("删除出库订单")
    public R deleteOutorder(@RequestBody List<Long> outorderids){
        if(outorderids.size()==0)
            return R.error().message("请选择列表中任一订单");
        try {
            for (int i = 0; i <outorderids.size() ; i++) {
                Outorder outorder = outorderService.getById(outorderids.get(i));
                if (outorder.getState().equals("3")){
                    return R.error().message("选中订单包含已分配的订单");
                }else if (outorder.getState().equals("4")){
                    return R.error().message("选中订单包含拣货中的订单");
                }else if (outorder.getState().equals("5")){
                    return R.error().message("选中订单包含已完成的订单");
                }
            }
            for (int i = 0; i < outorderids.size(); i++) {
                outorderService.removeById(outorderids.get(i));
            }
            for (int i = 0; i <outorderids.size() ; i++) {
                R r = outorderDetailService.findAllOUtorderdetailById(outorderids.get(i));
                for (int j = 0; j <r.getData().size(); j++) {
                    OutorderDetail outorderDetail= (OutorderDetail) r.getData().get(i);
                    if (outorderDetail!=null){
                        outorderDetailService.removeById(outorderDetail.getId());
                    }
                }
            }
            return R.ok().message("删除成功");
        }catch (Exception e){
            return R.error().message("删除失败");
        }
    }

    @GetMapping("changeOutorderState")
    @ApiOperation("改变出库订单为待审核状态")
    public R changeOutorderState(Long outordedrid){
        List<Long> list=new ArrayList<>();
        list.add(outordedrid);
        Outorder outorder = outorderService.getById(outordedrid);
        QueryWrapper<OutorderDetail> wrapper=new QueryWrapper<>();
        wrapper.eq("pid",outordedrid);
        List<OutorderDetail> list1 = outorderDetailService.list(wrapper);
        int num=0;
        for (int i = 0; i <list1.size() ; i++) {
            num=num+list1.get(i).getQty();
        }
        outorder.setQty(num);
        return outorderService.changestate(list,"1");
    }

    @GetMapping("findallOutorder")
    @ApiOperation("查询所有出库订单（下拉使用）")
    public R findallOutorder(){
        QueryWrapper<Outorder> wrapper=new QueryWrapper<>();
        wrapper.eq("state","5");
        List<Outorder> list = outorderService.list(wrapper);
        return R.ok().message("查询成功").data("outorderList",list);
    }
    @GetMapping("overOutorder/{id}")
    @ApiOperation("结束出库")
    public R overOutorder(@PathVariable("id") Long outoerderid){
        try{
            QueryWrapper<OutorderDetail> wrapper=new QueryWrapper<>();
            wrapper.eq("pid",outoerderid);
            List<OutorderDetail> list1 = outorderDetailService.list(wrapper);
            if (list1.size()==0){
                return R.error().message("此订单中没有记录，不能结束！");
            }else{
                int num=0;
                for (int i = 0; i <list1.size(); i++) {
                    num=num+list1.get(i).getQty();
                }
                QueryWrapper<Outorder> wrapper1=new QueryWrapper<>();
                wrapper1.eq("id",outoerderid);
                Outorder outorder=new Outorder();
                outorder.setQty(num);
                outorderService.update(outorder,wrapper1);
            }
            List list=new ArrayList();
            list.add(outoerderid);
            outorderService.changestate(list,"1");
            return R.ok().message("结束成功，待审核");
        }catch (RuntimeException e){
            return R.error().message("结束失败");
        }
    }
}

